var mysql = require('mysql'),
    http = require('http'),
    url = require('url'),
    crypto = require('crypto'),
    querystring = require('querystring'),
    config = require('./config.js');
const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    // res.writeHead(200, { 'Content-Type': 'text/plain' });
    // res.setHeader('Content-Type', 'text/html');
    // res.write(weibo());
    weibo(res);
    // res.end(txt + 'hehe');
});

function weibo(res) {
    var client = createMySQLClient();
    var sql = "select nickname, content, created_time, device from weibo limit 10";
    var txt = '';
    client.query(sql, function(err, data) {
        if (err) {
            log('error:' + err.message);
            return false;
        } else {
            data.forEach(function(v) {
                txt = txt + JSON.stringify(v);
                //log(v);
            });
            res.end(txt);
            //return txt;
        }
    });
    client.end();
}

function createMySQLClient() {
    var conn = mysql.createConnection(config.dbinfo);
    conn.connect(function(error, results) {
        if (error) {
            console.log('Connection Error: ' + error.message);
            return;
        }
        console.log('Connected to MySQL');
    });
    return conn;
}
server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});